if '__main__' == __name__:

    xdata = [
        [1, 2],
        [8, 9],
        [8, 7],
        [10, -1],
        [5, 6],
        [3, 4],
        [5, 4]
    ]

    num2set_map = dict()

    for xpair in xdata:
        x, y = xpair

        set_x = num2set_map.get(x, None)
        set_y = num2set_map.get(y, None)

        if -1 == x and -1 == y:
            continue
        elif -1 == y:
            if set_x is not None:
                continue
            else:
                num2set_map[x] = set([x])
                continue
        elif -1 == x:
            if set_y is not None:
                continue
            else:
                num2set_map[y] = set([y])
                continue

        # -1 != x and -1 != y

        if set_x is None and set_y is None:
            set_xy = set([x, y])
            num2set_map[y] = set_xy
            num2set_map[x] = set_xy
            continue
        elif set_y is None:
            set_x.add(y)
            num2set_map[y] = set_x
            continue
        elif set_x is None:
            set_y.add(x)
            num2set_map[x] = set_y
            continue
        else:
            if set_x == set_y:  # already associated
                continue
            else:
                set_xy = set_x.union(set_y)
                num2set_map[y] = set_xy
                num2set_map[x] = set_xy

        print('Before merging')
        print(num2set_map)

        print('Merging ...')
        xpass = 0
        while True:
            xpass += 1
            print('Pass', xpass)
            xrestart = False
            for xnum, xset in num2set_map.items():
                if xrestart:
                    break
                for xnum_in_set in xset:
                    if xnum_in_set == xnum:
                        continue
                    xset2 = num2set_map[xnum_in_set]
                    if xset != xset2:
                        xrestart = True
                        xset_merged = xset.union(xset2)
                        num2set_map[xnum] = xset_merged
                        num2set_map[xnum_in_set] = xset_merged
                        print('Merged', xnum, xnum_in_set)
                        break
            if not xrestart:
                break
        print('Merged.')

    print('Result')
    xsets = set()
    for xset in num2set_map.values():
        xsets.add(tuple(sorted(list(xset))))

    print(sorted(xsets))
